<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加密工具增强版</title>
    <script src="https://cdn.jsdelivr.net/npm/crypto-js@4.1.1/crypto-js.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/sm-crypto/0.3.2/sm-crypto.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .container {
            background-color: #f9f9f9;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .section {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #fff;
            border-radius: 5px;
            border: 1px solid #eee;
        }
        textarea, input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
        }
        textarea {
            height: 100px;
        }
        select, button {
            padding: 10px 15px;
            margin-right: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #fff;
            cursor: pointer;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button.secondary {
            background-color: #2196F3;
        }
        button.secondary:hover {
            background-color: #0b7dda;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            background-color: #e9e9e9;
            border-radius: 4px;
            word-wrap: break-word;
        }
        .key-group {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        .key-group input {
            flex: 1;
        }
        .info {
            font-size: 0.9em;
            color: #666;
            margin-top: 5px;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            border-bottom: none;
            border-radius: 5px 5px 0 0;
        }
        .tab.active {
            background-color: #f9f9f9;
            border-color: #ddd #ddd #f9f9f9;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>加密工具增强版</h1>
        
        <div class="tabs">
            <div class="tab active" onclick="switchTab('encrypt')">加密工具</div>
            <div class="tab" onclick="switchTab('generate')">密钥生成</div>
        </div>
        
        <div id="encryptTab" class="tab-content active">
            <div class="section">
                <h3>加密工具</h3>
                <div id="libError" class="error" style="display: none;">
                    警告：SM加密库加载失败，部分国密算法可能无法使用。请检查网络连接或使用本地文件。
                </div>
                
                <label for="inputText">输入文本:</label>
                <textarea id="inputText" placeholder="请输入要加密的文本..."></textarea>
                
                <label for="encryptionMethod">加密方式:</label>
                <select id="encryptionMethod">
                    <option value="md5">MD5</option>
                    <option value="sha256">SHA-256</option>
                    <option value="aes">AES</option>
                    <option value="sm3">SM3 (国密)</option>
                    <option value="sm4">SM4 (国密)</option>
                </select>
                
                <div id="keyContainer" style="display: none;">
                    <div class="key-group">
                        <input type="text" id="keyInput" placeholder="请输入密钥...">
                        <button onclick="generateKey()" class="secondary">生成密钥</button>
                    </div>
                    <div class="info">
                        AES密钥长度: 16/24/32字节 | SM4密钥长度: 16字节
                    </div>
                </div>
                
                <button id="encryptBtn">加密</button>
                <button id="clearBtn">清空</button>
                
                <div>
                    <label>加密结果:</label>
                    <div id="result" class="result"></div>
                </div>
            </div>
        </div>
        
        <div id="generateTab" class="tab-content">
            <div class="section">
                <h3>密钥生成器</h3>
                
                <label for="keyType">密钥类型:</label>
                <select id="keyType">
                    <option value="aes128">AES-128 (16字节)</option>
                    <option value="aes192">AES-192 (24字节)</option>
                    <option value="aes256">AES-256 (32字节)</option>
                    <option value="sm4">SM4 (16字节)</option>
                    <option value="random">随机字符串</option>
                </select>
                
                <div id="randomLengthContainer" style="display: none;">
                    <label for="randomLength">长度:</label>
                    <input type="number" id="randomLength" value="16" min="1" max="128">
                </div>
                
                <button onclick="generateKeyStandalone()">生成密钥</button>
                
                <div>
                    <label>生成的密钥:</label>
                    <div id="generatedKey" class="result"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 检查库是否加载成功
        if (typeof smCrypto === 'undefined') {
            document.getElementById('libError').style.display = 'block';
        }
        
        // 切换标签页
        function switchTab(tabName) {
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            document.querySelector(`.tab[onclick="switchTab('${tabName}')"]`).classList.add('active');
            document.getElementById(`${tabName}Tab`).classList.add('active');
        }
        
        // 初始化页面元素
        document.addEventListener('DOMContentLoaded', function() {
            const encryptionMethod = document.getElementById('encryptionMethod');
            const keyContainer = document.getElementById('keyContainer');
            const keyType = document.getElementById('keyType');
            const randomLengthContainer = document.getElementById('randomLengthContainer');
            
            // 加密方式变化时显示/隐藏密钥输入框
            encryptionMethod.addEventListener('change', function() {
                const method = this.value;
                keyContainer.style.display = (method === 'aes' || method === 'sm4') ? 'block' : 'none';
            });
            
            // 密钥类型变化时显示/隐藏长度输入
            keyType.addEventListener('change', function() {
                randomLengthContainer.style.display = (this.value === 'random') ? 'block' : 'none';
            });
            
            // 加密按钮事件
            document.getElementById('encryptBtn').addEventListener('click', encrypt);
            
            // 清空按钮事件
            document.getElementById('clearBtn').addEventListener('click', function() {
                document.getElementById('inputText').value = '';
                document.getElementById('keyInput').value = '';
                document.getElementById('result').textContent = '';
            });
        });
        
        // 生成随机密钥
        function generateRandomKey(length, chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()') {
            let result = '';
            for (let i = 0; i < length; i++) {
                result += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return result;
        }
        
        // 生成随机字节密钥
        function generateRandomBytes(length) {
            const values = new Uint8Array(length);
            window.crypto.getRandomValues(values);
            return Array.from(values).map(b => b.toString(16).padStart(2, '0')).join('');
        }
        
        // 为加密工具生成密钥
        function generateKey() {
            const method = document.getElementById('encryptionMethod').value;
            let key = '';
            
            if (method === 'aes') {
                // 生成16/24/32字节的AES密钥
                const lengths = { 'aes': 16, 'aes192': 24, 'aes256': 32 };
                key = generateRandomBytes(16); // 默认16字节
            } else if (method === 'sm4') {
                // SM4需要16字节密钥
                key = generateRandomBytes(16);
            }
            
            document.getElementById('keyInput').value = key;
        }
        
        // 独立密钥生成器
        function generateKeyStandalone() {
            const keyType = document.getElementById('keyType').value;
            let key = '';
            
            switch(keyType) {
                case 'aes128':
                    key = generateRandomBytes(16);
                    break;
                case 'aes192':
                    key = generateRandomBytes(24);
                    break;
                case 'aes256':
                    key = generateRandomBytes(32);
                    break;
                case 'sm4':
                    key = generateRandomBytes(16);
                    break;
                case 'random':
                    const length = parseInt(document.getElementById('randomLength').value) || 16;
                    key = generateRandomKey(length);
                    break;
            }
            
            document.getElementById('generatedKey').textContent = key;
        }
        
        // 加密函数
        function encrypt() {
            const text = document.getElementById('inputText').value.trim();
            if (!text) {
                alert('请输入要加密的文本!');
                return;
            }
            
            const method = document.getElementById('encryptionMethod').value;
            const key = document.getElementById('keyInput').value.trim();
            
            try {
                let encryptedResult = '';
                
                switch(method) {
                    case 'md5':
                        encryptedResult = CryptoJS.MD5(text).toString();
                        break;
                        
                    case 'sha256':
                        encryptedResult = CryptoJS.SHA256(text).toString();
                        break;
                        
                    case 'aes':
                        if (!key) {
                            alert('AES加密需要密钥!');
                            return;
                        }
                        encryptedResult = aesEncrypt(text, key);
                        break;
                        
                    case 'sm3':
                        if (typeof smCrypto === 'undefined') {
                            throw new Error('SM3加密需要sm-crypto库，但库加载失败');
                        }
                        encryptedResult = smCrypto.sm3(text);
                        break;
                        
                    case 'sm4':
                        if (!key) {
                            alert('SM4加密需要密钥!');
                            return;
                        }
                        if (typeof smCrypto === 'undefined') {
                            throw new Error('SM4加密需要sm-crypto库，但库加载失败');
                        }
                        encryptedResult = sm4Encrypt(text, key);
                        break;
                }
                
                document.getElementById('result').textContent = encryptedResult;
            } catch (error) {
                document.getElementById('result').textContent = '加密出错: ' + error.message;
                console.error(error);
            }
        }
        
        // AES加密函数
        function aesEncrypt(text, key) {
            const keySize = key.length;
            if (keySize !== 16 && keySize !== 24 && keySize !== 32) {
                throw new Error('AES密钥长度应为16/24/32字节 (128/192/256位)');
            }
            
            const keyBytes = CryptoJS.enc.Utf8.parse(key);
            const iv = CryptoJS.enc.Utf8.parse(key.substring(0, 16)); // 使用密钥前16字节作为IV
            
            const encrypted = CryptoJS.AES.encrypt(text, keyBytes, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            });
            
            return encrypted.toString();
        }
        
        // SM4加密函数
        function sm4Encrypt(text, key) {
            const keySize = key.length;
            if (keySize !== 16) {
                throw new Error('SM4密钥长度应为16字节 (128位)');
            }
            
            const keyBytes = smCrypto.utils.utf8ToArray(key);
            const iv = smCrypto.utils.utf8ToArray(key.substring(0, 16)); // 使用密钥前16字节作为IV
            
            const encrypted = smCrypto.sm4.encrypt(
                smCrypto.utils.utf8ToArray(text), 
                keyBytes, 
                { iv: iv }
            );
            
            return smCrypto.utils.arrayToHex(encrypted);
        }
    </script>
</body>
</html>